package com.galeno.demo;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;


/**
 * @author galeno
 * @Title:
 * @Description: 实现一个卡夫卡的生产者
 * @date 2021/9/1022:27
 */
public class Productor {
    public static void main(String[] args) throws InterruptedException {
        Properties properties = new Properties();
        String serverUrl = "galeno01:9092,galeno02:9092,galeno03:9092";
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, serverUrl);
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            ProducerRecord<String, String> record = new ProducerRecord<String, String>(
                    "first",
                    StringUtils.leftPad(i + "", 8, "0"),
                    RandomStringUtils.randomAlphabetic(2).toUpperCase()
            );
            // 用生产者发送消息(kafka的producer底层数据发送都是使用的异步发送）
            producer.send(record);
            Thread.sleep(200, 2000);

        }

        producer.close();
    }
}
